﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.HomeServer.Extensibility;
using Microsoft.HomeServer.HomeServerConsoleTab.TV4Home.Server.WHS.AddIn.Controls;

namespace Microsoft.HomeServer.HomeServerConsoleTab.TV4Home.Server.WHS.AddIn.TabPageControls
{
    public partial class SetupTVTabUserControl : UserControl
    {
        public SetupTVTabUserControl()
        {
            InitializeComponent();
        }

        public bool IsInitialized
        {
            get;
            set;
        }

        public void Initialize()
        {
            new System.Threading.Thread(ThreadSafeLoadSetupTV).Start();

            this.IsInitialized = true;
        }

        private void ThreadSafeLoadSetupTV()
        {
            this.pnAppContainer.Invoke(new Action(LoadSetupTV));
        }

        private void LoadSetupTV()
        {
            this.pnAppContainer.Controls.Clear();
            this.pnAppContainer.Controls.Add(new SetupTVLoadingControl() { Dock = DockStyle.Fill });

            Process program = new Process();

            // kill running instances of SetupTV
            if (Process.GetProcessesByName("SetupTv").Length > 0)
            {
                Process.GetProcessesByName("SetupTv")[0].Kill();
                System.Threading.Thread.Sleep(100);
            }

            FileInfo setupTV = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Team MediaPortal\MediaPortal TV Server\SetupTv.exe");

            program.EnableRaisingEvents = true;
            program.Exited += new EventHandler(this.ProcessExited);
            program.StartInfo.FileName = setupTV.FullName;
            //program.StartInfo.Arguments = " ";
            program.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            program.StartInfo.WorkingDirectory = setupTV.DirectoryName;

            try
            {
                program.Start();
                program.WaitForInputIdle();

                while (program.MainWindowHandle == IntPtr.Zero || !program.MainWindowTitle.StartsWith("MediaPortal"))
                {
                    program.Refresh();
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(50);

                    if (program.HasExited)
                        return;
                }

                // store the current windows style
                long style = Utils.Win32.GetWindowLong(program.MainWindowHandle, Utils.Win32.GWL_STYLE);

                // flip the WS_CAPTION bits (-> removes title bar) and set the WS_CHILD bits (-> required for the toolbar buttons in the app to work)
                Utils.Win32.SetWindowLong(program.MainWindowHandle, Utils.Win32.GWL_STYLE, (int)((style ^= Utils.Win32.WS_CAPTION) | Utils.Win32.WS_CHILD));

                // place the app into the container panel
                Utils.Win32.SetParent(program.MainWindowHandle, this.pnAppContainer.Handle);

                // show the app
                Utils.Win32.ShowWindow(program.MainWindowHandle, Utils.Win32.SW_MAXIMIZE);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ProcessExited(object sender, EventArgs e)
        {
            this.pnAppContainer.Invoke(new Action(LoadSetupTVExitedControl));
        }

        private void LoadSetupTVExitedControl()
        {
            this.pnAppContainer.Controls.Clear();

            SetupTVClosedControl ctrl = new SetupTVClosedControl() { Dock = DockStyle.Fill };
            ctrl.SetupTVRestartRequested += delegate { ThreadSafeLoadSetupTV(); };

            this.pnAppContainer.Controls.Add(ctrl);
        }
    }
}
